#include <string>
#include <iostream>
#include "messages/SensorData.h"
#include "../plugins/jsoncpp1.9.0/json.h"

class SensorDataCollection {
public:
    int id;
    std::string location;
    std::vector<SensorData> data;

    std::string toJson() const {
        Json::Value root;
        root["id"] = id;
        root["location"] = location;

        Json::Value sensorData(Json::arrayValue);
        for (const auto& item : data) {
            Json::Value itemJson;
            itemJson["sensorName"] = item.sensorName;
            itemJson["value"] = item.value;
            itemJson["timestamp"] = item.timestamp;
            sensorData.append(itemJson);
        }
        root["data"] = sensorData;

        Json::StreamWriterBuilder jswBuilder;
        jswBuilder["emitUTF8"] = true;
        std::unique_ptr<Json::StreamWriter> jsWriter(jswBuilder.newStreamWriter());

        std::ostringstream os;
        jsWriter->write(root, &os);
        return os.str();
    }

    static SensorDataCollection fromJson(const std::string& jsonStr) {
        Json::Value root;
        Json::CharReaderBuilder builder;
        std::istringstream iss(jsonStr);
        std::string errs;
        if (!Json::parseFromStream(builder, iss, &root, &errs)) {
            throw std::runtime_error("Failed to parse JSON: " + errs);
        }

        SensorDataCollection collection;
        collection.id = root["id"].asInt();
        collection.location = root["location"].asString();

        const Json::Value sensorData = root["data"];
        for (const auto& itemJson : sensorData) {
            SensorData item;
            item.sensorName = itemJson["sensorName"].asString();
            item.value = itemJson["value"].asDouble();
            item.timestamp = itemJson["timestamp"].asString();
            collection.data.push_back(item);
        }

        return collection;
    }
};